<!-- 组织详情组织信息 -->
<template>
  <div class="container">
    <a-scrollbar
      style="height: calc(100vh - 216px); overflow: auto; padding: 0 10px"
      id="scrollBar"
      type="track"
      @scroll="handleScroll"
    >
      <div
        v-for="(item, index) in data"
        :key="index"
        :id="item.collectionId"
        :ref="`${item.collectionId}`"
      >
        <div :id="item.collectionId">
          <div class="title-box">
            <div class="title">
              <div
                :style="{
                  marginLeft: '25px'
                }"
              >
                {{ item.collectionName }}
              </div>
              <div>
                <a-tooltip content="编辑信息">
                  <icon-font
                    v-show="currCollectionId !== item.collectionId"
                    :style="{
                      cursor: 'pointer'
                    }"
                    type="icon-edit"
                    :size="36"
                    @click="edit(item.collectionId)"
                  ></icon-font>
                </a-tooltip>
              </div>
            </div>
          </div>

          <a-form :model="item" ref="formRef" autoLabelWidth>
            <a-row :gutter="16">
              <a-col
                v-for="item2 in item.controlItems"
                :key="item2.id"
                :span="item2.span"
              >
                <FormItem
                  :name="item2.ctlCnName"
                  :componentType="item2.ctlComponentType"
                  :code="item2.ctlCode"
                  :props="item2.props"
                  v-model:values="item2.ctlValue"
                  :required="false"
                  :validateRules="
                    checkEnums.includes(item2.ctlCode) ? validate : null
                  "
                  :disabled="
                    currCollectionId !== item.collectionId ||
                    forbidEditEnum.includes(item2.ctlCode)
                  "
                  :data="item2"
                ></FormItem>
              </a-col>
            </a-row>
          </a-form>

          <a-space
            v-if="currCollectionId === item.collectionId"
            class="btns"
            size="large"
          >
            <a-button @click="cancel">取消</a-button>
            <a-button type="primary" @click="save(index)">保存</a-button>
          </a-space>
        </div>
      </div>
    </a-scrollbar>

    <div v-if="scroll" class="anchor">
      <div
        class="anchor-total"
        v-for="item in data"
        :key="item.collectionId"
        @click="handleAnchor(item.collectionId)"
        :class="{ active: item.collectionId === currAnchorId }"
        :ref="(e, ind) => setAnchorRefs(e, item.collectionId)"
      >
        <div class="anchor-total-box">
          <div
            class="anchor-total-box-circle"
            :class="{ activeCircle: item.collectionId === currAnchorId }"
          ></div>
          <div class="anchor-total-box-item">
            {{ item.collectionName }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  GetOrganizationListDetail,
  PutOrganizationListDetail,
  GetOrganizationHeaderSetting,
  PutOrganizationHeaderSetting,
  GetCheckOrganization
} from '@/apis/management/organization/organizationManagement';
import { GetBusinessModalData } from '@/apis/controltotal';
import { GetPositionDefault } from '@/apis/management/organization/positionManagement';
import {
  GetHumanRosterDetail,
  GetHumanRosterList
} from '@/apis/management/human/humanRoster';
import { placeSplice } from '@/utils/utils';
import { Message } from '@arco-design/web-vue';
import { cloneDeep } from 'lodash';
import { validateRules } from '@/utils/common';
import FormItem from '@/components/DynamicFormsNew/RenderingForm/FormItem/index.vue';
import { GetHeaderSetting } from '@/apis/management/base';
import useControlFormStore from '@/store/controlForm';
const controlFormStore = useControlFormStore();
controlFormStore.fieldNames.labelName = 'ctlCnName';
controlFormStore.fieldNames.componentType = 'ctlComponentType';
controlFormStore.fieldNames.valueName = 'ctlValue';
const route = useRoute();

// 档案id
let id = Number(route.query.id);
let ownerType = Number(route.query.ownerType);

onBeforeRouteUpdate((to) => {
  id = Number(to.query.id);
  ownerType = Number(to.query.ownerType);
  getData();
});

let currAnchorId = ref(-1); // 当前选中锚点的id

let scroll = ref(); // 定义一个scroll储存scrollbar的Dom用来锚点跳转

onMounted(() => {
  scroll.value = document.getElementById('scrollBar');
});

const orginData = ref(); // 原始数据

let formRef = ref();

let origin = {
  name: '',
  code: '',
  superiorId: 0
};

let checkEnums = [
  'C30BBF36A5AF541F7A2657671DEE2EDD6',
  'CB1AAC9E508714223BA4D1596FE690877'
];

// 组织名称、组织编码查重
const validate = async (val: any, code: string) => {
  try {
    if (!val) return;
    /*
      type 1为组织名称 2组织编码
    */
    let type = 0,
      flag = false; // 判断原来的值和当前的值是否相等, 如果相等则返回null
    // 组织名称
    if (code === 'C30BBF36A5AF541F7A2657671DEE2EDD6') {
      type = 1;
      if (val === origin.name) flag = true;
    }
    // 组织编码
    else if (code === 'CB1AAC9E508714223BA4D1596FE690877') {
      type = 2;
      if (val === origin.code) flag = true;
    }
    if (!flag) {
      const data = {
        superiorId: origin.superiorId || 0,
        type,
        name: val
      };
      const res = await validateRules(GetCheckOrganization, data);
      if (res.code) {
        return `${res.data}`;
      }
    }
    return null;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 拼用来数据的数据
const data = reactive([
  {
    collectionId: undefined,
    collectionName: '',
    controlItems: [] as any
  }
]);
let formHeader = ref<any>([]);
// 不能修改的项 上级组织、组织类型
const forbidEditEnum = [
  'C073F4F41C46D4CA3AF3BEC1F51A8F410',
  'C3D33FA57216F4968BDE51C31D623FC09'
];

// 获取详情数据
const getData = async () => {
  try {
    const [organizationDetail, headerSettingRes, businessModalData] =
      await Promise.all([
        GetOrganizationListDetail({ id, ownerType }),
        GetHeaderSetting({
          ownerFuncType: 1,
          userId: +(localStorage.getItem('userId') as string)
        }),
        GetBusinessModalData({
          funcCode: 'SER_FUNCFA65A09668D949CEB25F5AD3B233F6E0'
        })
      ]);
    orginData.value = organizationDetail.useTemplate.collectionModel;
    formHeader.value = [];
    const headerChildren = businessModalData.funcCtlInfos.children;
    headerChildren?.forEach((child: any, index: number) => {
      formHeader.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail?.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    let collectionIdArr: any = []; // 储存有多少不同的collectionId
    console.log('=========orginData===========================');
    console.log(organizationDetail);
    console.log('====================================');
    orginData.value?.forEach((item: any) => {
      /* 储存唯一的collectionId */
      if (!collectionIdArr.includes(item.id)) collectionIdArr.push(item.id);
      item.controlModel?.forEach((item2: any) => {
        let value = item2.ctlValue.ctlValue;
        if (
          // 组织名称
          item2.ctlCode === 'C30BBF36A5AF541F7A2657671DEE2EDD6'
        )
          origin.name = value;
        else if (
          // 组织编码
          item2.ctlCode === 'CB1AAC9E508714223BA4D1596FE690877'
        )
          origin.code = value;
        else if (
          // 上级组织
          item2.ctlCode === 'C073F4F41C46D4CA3AF3BEC1F51A8F410'
        )
          origin.superiorId = +value;
      });
    });

    /* 每次先将数组清空再赋一个空对象然后传入唯一的collectionId */
    data.length = 0;

    collectionIdArr?.forEach((item: any, index: any) => {
      data.push({
        collectionId: undefined,
        collectionName: '',
        controlItems: []
      });
      data[index].collectionId = item;
    });

    // 循环赋值
    data?.forEach((item1: any) => {
      orginData.value?.forEach((item2: any) => {
        item2.controlModel?.forEach((item3: any) => {
          let ctlCode = item3.ctlCode,
            ctlValue = item3.ctlValue.ctlValue;
          if (item1.collectionId === item2.id) {
            if (item1.collectionName === '')
              item1.collectionName = item2.cnName;
            item1.controlItems.push({
              controlId: item3.id,
              collectionId: item2.collectionId,
              orderNo: item2.orderNo,

              // 如果ctlCode是以下的值就要转为Number类型的值
              ctlValue:
                isNaN(+ctlValue) && ctlValue !== 'undefined'
                  ? ctlValue
                  : ctlValue === ''
                  ? ''
                  : ctlValue == 'undefined'
                  ? undefined
                  : +ctlValue,
              id: item3.ctlValue.id,
              ctlCnName: item3.ctlCnName,
              ctlCode: ctlCode,
              code: ctlCode,
              ctlComponentType: item3.ctlComponentType,
              props: JSON.parse(item3.props),
              required: item3.required,
              span: item3.span
            });
          }
        });
      });
    });
    currAnchorId.value = data[0].collectionId;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let currCollectionId = ref(0); // 储存当前选中子类的collectionId，用来编辑
const eleAnchorRefs = ref([]); // 储存锚点的refs

// 动态设置锚点的refs
const setAnchorRefs = (e, ind) => {
  eleAnchorRefs.value[ind] = e;
};
// 处理锚点数据
const handleAnchor = (id: number) => {
  currAnchorId.value = id;
  eleAnchorRefs.value[id]?.scrollIntoView({
    behavior: 'smooth'
  });
  let targetElement = document.getElementById(`${id}`);
  let targetOffset = targetElement?.offsetTop;
  // 获取包含目标元素的父级 div
  let parentDiv = document.getElementById('scrollBar'); // 将 'your-parent-div-id' 替换为实际的父级 div 的 id
  // 平滑滚动到目标位置
  parentDiv.scrollTo({
    top: targetOffset,
    behavior: 'smooth'
  });
};

// 编辑按钮
const edit = (collectionId: number | undefined) => {
  if (currCollectionId.value !== collectionId)
    currCollectionId.value = collectionId as number;
  else currCollectionId.value = 0;
};

// 编辑取消按钮
const cancel = () => {
  currCollectionId.value = 0;
};

const placeCtlCode = [
  'C02BE308AEE674E3F95335AED60682954',
  'CF058C6BF648940BA96B49495CC768E20'
]; //户籍所在地、籍贯相关code
// 重组树形数据所需子方法
const controldataTreeFilter = (treeData: any) => {
  const temp = treeData?.map((item2: any) => ({
    // 将控件的code赋值对应的value
    [item2.code]:
      // 如果是户籍所在地、籍贯
      placeCtlCode.includes(item2.code) ? placeSplice(item2.value) : item2.value
  }));
  let obj = {};
  temp?.forEach((item: any) => {
    obj = { ...obj, ...item };
  });
  return obj;
};

const dataFilter = (data: any) => {
  const arr = data?.map((item: any) => ({
    ...item,
    ...controldataTreeFilter(item.positionDetailData)
  }));
  return arr;
};

// 保存某一部分表单
const save = async (index: number) => {
  try {
    let temp = cloneDeep(data[index].controlItems);
    let hasResponsibleControl = false; // 判断该子集是否存在组织负责人控件
    const extraData = reactive<any>({
      responseInfo: {}, // 储存组织负责人信息
      positionInfo: {}, // 储存职位信息
      leaderInfo: {
        id: [],
        name: []
      }, // 储存分管领导信息
      name: '', // 储存公司名
      ownerId: undefined // 储存组织类型
    });
    // 对要传的控件属性进行过滤
    temp.forEach((item: any) => {
      // item.value = item.value;
      formHeader.value.forEach((item2: any) => {
        if (item2.code === item.code) item.code = item2.code;
      });

      // 如果有组织负责人控件
      if (item.code === 'CB0C63F38283045F58FFF1B1EABE5D151')
        hasResponsibleControl = true;
      // 如果有组织名称控件
      else if (item.code === 'C30BBF36A5AF541F7A2657671DEE2EDD6')
        extraData.name = item.ctlValue + '';
      // 如果有组织类型控件
      else if (item.code === 'C3D33FA57216F4968BDE51C31D623FC09')
        extraData.ownerId = item.ctlValue + '';
      // 如果有编制人数控件
      else if (item.code === 'CD25749DBA68E4BF3BCA616DD63751CB7')
        extraData.headcount = item.ctlValue + '';

      // 将value赋值成string类型的才能传给后端
      item.ctlValue = item.ctlValue + '';
      delete item.ctlCnName;
      delete item.ctlCode;
      delete item.ctlComponentType;
      delete item.props;
      delete item.required;
      delete item.span;
    });
    console.log(temp);

    // 编辑之前先校验
    formRef.value[index].validate(async (valid: any) => {
      if (valid === undefined) {
        // 如果要修改包含组织负责人控件的
        if (hasResponsibleControl) {
          // 获取全部人员信息
          let { content: humanContent } = await GetHumanRosterList({
            pageNumber: 0,
            pageSize: -1,
            typeName: '4,5,6,9,10,11,12,13,14,15'
          });
          // 查找对应组织负责人的信息
          extraData.responseInfo = humanContent.find(
            (item: any) =>
              item.id ==
              +temp.find(
                (item: any) => item.code === 'CB0C63F38283045F58FFF1B1EABE5D151'
              )?.ctlValue
          );

          // 查找对应分管领导的信息
          const leaderInfoCtlValueArr = temp
            .find((el: any) => el.code === 'CA6BD9CC1C99D4D13AD4F5009EF4F9586')
            .ctlValue.split(',');

          leaderInfoCtlValueArr.forEach((el: any) => {
            const tempInfo = humanContent.find((item: any) => item.id === +el);
            extraData.leaderInfo.id.push(tempInfo?.id);
            extraData.leaderInfo.name.push(tempInfo?.name);
          });
          if (extraData.responseInfo) {
            // 获取职位信息
            extraData.positionInfo = await GetPositionDefault({
              id: +extraData.responseInfo?.positionId
            });
          }

          await PutOrganizationListDetail({
            listModel: {
              // templateUseId: id,
              responsibleId: +extraData.responseInfo?.id,
              responserName: extraData.responseInfo?.name,
              positionName: extraData.positionInfo?.name,
              name: extraData?.name,
              headcount: +extraData?.headcount,
              leaderId: extraData.leaderInfo?.id.join(','),
              leaderName: extraData.leaderInfo?.name.join(','),
              // type: 2,
              ownerId: +extraData?.ownerId,
              id
            },
            ctlValue: temp
          });
          currCollectionId.value = 0;
        } else {
          await PutOrganizationListDetail({
            ctlValue: temp
            // organizationList: {
            //   type: 2,
            //   organizationalData: temp
            // }
          });
          currCollectionId.value = 0;
        }
      } else {
        Message.error('请填写必填的信息！');
      }
    });
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style scoped lang="less">
.container {
  display: flex;
  .anchor {
    padding-left: 20px;
    display: flex;
    flex-direction: column;
    &-total {
      display: inline-block;
      text-decoration: none;
      color: #000;
      height: 36px;
      line-height: 36px;
      z-index: 9;
      &:last-child .anchor-total-box-circle::after {
        content: none; /* 移除连线样式 */
      }
      &-box {
        width: 120px;
        position: relative;
        display: flex;
        align-items: center;

        &:active,
        &:hover {
          background-color: #edeffd;
        }

        &-item {
          position: relative;
          font-weight: 700;
          text-align: left;
        }
        &-circle {
          position: relative;
          right: 10px;
          width: 10px;
          height: 10px;
          box-shadow: 0 0 0 4px #edeffd;
          border-radius: 50%;
          background-color: #ccc;

          &::after {
            position: absolute;
            content: '';
            width: 2px; /* 线条的宽度 */
            height: calc(20px); /* 线条的高度 */
            background-color: #ccc; /* 线条的颜色 */
            bottom: -24px; /* 将线条放置在圆形下面 */
            left: 50%; /* 将线条水平居中 */
            transform: translateX(-1px); /* 修正水平居中的偏移 */
          }
        }
      }
    }
  }
  .title-box {
    position: relative;
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 36px;
      border-radius: 4px;
      font-weight: 700;
      margin-bottom: 10px;
      background: #edeffd;
    }
  }

  .title-box::before {
    position: absolute;
    // top: 33px;
    left: 10px;
    display: inline-block;
    height: 18px;
    top: 50%;
    transform: translateY(-50%);
    width: 10px;
    margin-right: 20px;
    border-radius: 2px;
    content: '';
    background-color: #165dff;
  }
  .btns {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    margin-bottom: 10px;
  }
}
:deep(.arco-anchor-link-active) {
  background-color: #edeffd;
}
.active {
  color: #165dff !important;
}

.activeCircle {
  background-color: #165dff !important;
}
</style>
